package com.lr.springbootdemo.custom;

import com.lr.springbootdemo.bean.Constants;
import com.lr.springbootdemo.bean.Result;
import com.lr.springbootdemo.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * .统一拦截处理
 * Created by li.rui on 2016-06-15.
 */
public class CustomInterceptor implements HandlerInterceptor {
    private static Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        logger.info("preHandle...");
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        if ("/".equals(contextPath)){contextPath = "";}
        String method = uri.replaceFirst(contextPath,"");
        logger.info("******uri:  " + request.getRequestURI());
        logger.info("******param:  " + JsonUtil.object2String(request.getParameterMap()));
        if ("/error".equals(method)){
            Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
            //如果是错误页面
            Result result = new Result();
            result.setMsg("statusCode:"+statusCode);
            result.setStatus(Constants.ERROR);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            PrintWriter writer = response.getWriter();
            writer.write(result.toString());
            writer.flush();
            writer.close();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("postHandle...");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("afterCompletion...");
    }
}
